<?php
class login extends CI_Controller{
	
	protected $login_m = 'Login_m';
	protected $now = null ;
	
	function index(){		
		$this->load->model($this->login_m,'',true);	
		$this->load->view('Login_v');
	}
	
	function auth(){
		$this->load->model($this->login_m,'',true);	
		$username = $this->input->post('Tusername');
		$pass = $this->input->post('Tpassword');
		$trans = array('email'=>$username,'password'=>$pass);
		if($this->Login_m->auth($trans)== true):
			$this->session->set_userdata($this->Login_m->auth($trans));
			/* save to log on log in */
			$this->saveToLog($this->Login_m->auth($trans));
			redirect('memo');
		else:
			$this->session->set_flashdata('message','username dan password tidak cocok');
			redirect('login');	
		endif;
		
		
	} 	
	function logout(){
	$this->now =  date("Y-m-d G:i:s") ;
		$this->load->model($this->login_m,'',true);
		$userid = $this->session->userdata('user_id');
		$dataUpd = array('logout_date'=>$this->now,'status'=>'0');
		$this->Login_m->updatelog($dataUpd,$userid);	
		$this->session->sess_destroy();
		redirect('login');
	}
	
	// open  register form
	function register(){
		$this->load->view('register_v');
	}
	/*save data while log in 
	get param from select users table */
	
	function saveToLog($param){
		$userid = $param['user_id'];
		$this->now =  date("Y-m-d G:i:s") ;
		$data = array('user_id'=>$userid,'login_date'=>$this->now,'status'=>'1');
		if($this->Login_m->checkLog(array('user_id'=>$userid)) != null ):
		$dataUpd = array('login_date'=>$this->now,'status'=>'1');
		$this->Login_m->updatelog($dataUpd,$userid);	
		else:
		$this->Login_m->savelog($data);	
		endif;
	}
		
	function Preg(){	
		$this->load->model($this->login_m,'',true);	
		$this->now =  date("Y-m-d G:i:s") ;
		
		$this->form_validation->set_rules('Temail', 'Email', 'required');
		$this->form_validation->set_rules('Tfname', 'First Name', 'required');
		$this->form_validation->set_rules('Tlname', 'Last Name', 'required');
		$this->form_validation->set_rules('Tpassword', 'Password', 'required');		
		$this->form_validation->set_rules('Tpassconf', 'Password Confirmation', 'required');
		$this->form_validation->set_rules('Temail', 'Email', 'required');
		
		if($this->form_validation->run() == TRUE):
			if($this->input->post('Tpassword') == $this->input->post('Tpassconf')):
				$data = array('email'=>$this->input->post('Temail'),
							'password'=>$this->input->post('Tpassword'),
							'firstname'=>$this->input->post('Tfname'),
							'lastname'=>$this->input->post('Tlname'),
							'date_created'=>$this->now) ;
				$this->Login_m->register($data);
				$this->session->set_flashdata('message','anda berhasil mendaftar');
				redirect('login/');
			else:
			$this->session->set_flashdata('message','password dan konfirmasi tidak sama');
				redirect('login/register');
			endif;
		else:
			$this->load->view('register_v');
		endif;	
			
	}
	
}
?>